package com.ying.dogying.config;

import cn.hutool.core.map.MapUtil;
import com.ying.dogying.shiro.AccountRealm;
import com.ying.dogying.shiro.AuthFilter;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
	private static Logger log = LoggerFactory.getLogger(ShiroConfig.class);
    @Bean
    public SecurityManager securityManager(AccountRealm accountRealm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(accountRealm);

        log.info("ShiroConfig---------------->注入成功SecurityManager");
        return defaultWebSecurityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 配置登录的url
        shiroFilterFactoryBean.setLoginUrl("/im-user/login");
        // 配置登录成功的url
        shiroFilterFactoryBean.setSuccessUrl("/im-userInfo/center");
        // 配置未授权跳转的url
        shiroFilterFactoryBean.setUnauthorizedUrl("/error/403");
        shiroFilterFactoryBean.setFilters(MapUtil.of("auth", authFilter()));

        Map<String, String> map = new LinkedHashMap<>();

        // res
        map.put("/res/**", "anon");
        // 登录权限
        map.put("/im-user/login", "anon");
        // 注册权限
        map.put("/im-user/register", "anon");

        // 编辑文章
        map.put("/im-post/edit", "auth");
        // 我的主页
        map.put("/im-userInfo/home", "auth");
        // 我的发布
        map.put("/im-userInfo/myPublishedPost", "auth");
        // 我的收藏
        map.put("/im-userInfo/myCollectionPost", "auth");
        // 个人中心
        map.put("/im-userInfo/center", "auth");
        // 图片上传
        map.put("/im-userInfo/upload", "auth");
        // 基本设置
        map.put("/im-userInfo/basicSetup", "auth");
        // 我的消息
        map.put("/im-userInfo/message", "auth");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }

    @Bean
    public AuthFilter authFilter() {
        return new AuthFilter();
    }

}
